import {
  reqGetUserCode,
  reqUserLogin,
  reqUserRegister,
  reqUserInfo,
  reqUserLogout,
} from "@/api";
import { getTOKEN, removeToken, setTOKEN } from "@/utils/token";

// 用户仓库管理模块
const actions = {
  //验证码获取actions
  async getCode({ commit }, phone) {
    let result = await reqGetUserCode(phone);
    if (result.code == 200) {
      commit("SETCODE", result.data);
    } else {
      return Promise.reject(new Error("failure"));
    }
  },

  //用户注册
  async getUserRegister({ commit }, user) {
    let result = await reqUserRegister(user);
    console.log(result);
    if (result.code == 200) {
      return "success";
    } else {
      return Promise.reject(new Error("failure"));
    }
  },

  //用户登录
  async getUserLogin({ commit }, user) {
    let result = await reqUserLogin(user);
    console.log(result);
    if (result.code == 200) {
      //若token不存在
      // 存储用户token
      setTOKEN(result.data.token);
      commit("SETUSERLOGIN", result.data.token); //将token提交
      return "success";
    } else {
      return Promise.reject(new Error("failure"));
    }
  },

  //获取用户信息
  async getUserInfo({ commit }) {
    let result = await reqUserInfo();
   //console.log(result);
    if (result.code == 200) {
      commit("SETUSERINFO", result.data);
    } else {
      
    }
  },

  //用户退出登录
  async getUserLogout({ commit }) {
    let result = await reqUserLogout();
    if(result.code == 200){
      // 不建议在actions中处理state中的数据，若如此开发者工具检测不到数据变化
      //交给mutations处理数据
      commit("SETCLEARUSERINFO");
      return "success";
    } else{
      return Promise.reject(new Error('failure'));
    }
  },
};
const mutations = {
  //验证码获取
  SETCODE(state, value) {
    state.code = value || "";
  },

  // 获取token
  SETUSERLOGIN(state, value) {
    state.token = value;
  },

  // 获取用户信息
  SETUSERINFO(state, value) {
    state.user = value;
  },

  //用户相关数据清空
  SETCLEARUSERINFO(state){
    state.user = {}; 
    state.token = '';
    removeToken();
  }
};
const state = {
  code: "", //验证码
  token: getTOKEN(), //用户令牌
  user: {}, //用户信息
};
const getters = {};

export default {
  //默认暴露
  namespaced: true,
  actions,
  mutations,
  state,
  getters,
};
